package cn.xiaobai.subscriber;

import cn.xiaobai.annotaion.OnEvent;
import cn.xiaobai.annotaion.OnSubscribe;
import cn.xiaobai.annotaion.OnUnsubscribe;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @Author yangdaji
 * @Date 2023/11/2
 * @PackageName cn.xiaobai.subscriber
 * @ClassName RedisEventBusSubscriber
 */
public class RedisEventBusSubscriber {


    private Method onSubscribe;
    private Method onUnSubscribe;
    private Method onMessage;
    private Object subscribeProxy;


    public RedisEventBusSubscriber(Object subscribeProxy) {
        this.subscribeProxy = subscribeProxy;
    }

    public void onMessage(String message) {

        try {
            ReflectionUtils.invokeMethod(onMessage, subscribeProxy, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onSubscribe(String channel) {

        try {
            ReflectionUtils.invokeMethod(onSubscribe, subscribeProxy, channel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onUnSubscribe(String channel) {

        try {
            ReflectionUtils.invokeMethod(onUnSubscribe, subscribeProxy, channel);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void bindProxy() {

        // 反射获取目标代理类中的注解方法, 并进行赋值
        Method[] declaredMethods = subscribeProxy.getClass().getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            OnEvent onEvent = declaredMethod.getAnnotation(OnEvent.class);
            if (onEvent != null) {
                this.onMessage = declaredMethod;
            }
            OnSubscribe onSubscribe = declaredMethod.getAnnotation(OnSubscribe.class);
            if (onSubscribe != null) {
                this.onSubscribe = declaredMethod;
            }
            OnUnsubscribe onUnsubscribe = declaredMethod.getAnnotation(OnUnsubscribe.class);
            if (onUnsubscribe != null) {
                this.onUnSubscribe = declaredMethod;
            }
        }
    }
}
